/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.tutwiz.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.tutwiz.model.Step;
import net.tutwiz.model.Tutorial;
import net.tutwiz.persistence.StepPersistenceManager;
import net.tutwiz.persistence.TutorialPersistenceManager;

/**
 *
 * @author viktor
 */
public class StepController extends Controller {

//    @EJB
    private StepPersistenceManager stepPm = new StepPersistenceManager();
    private TutorialPersistenceManager tutPm = new TutorialPersistenceManager();

    public StepController(String[] params, HttpServletRequest request, HttpServletResponse response) {
        super(params, request, response);
    }

	// Anropar metoden för den action som ska köras
    @Override
    public void doAction() {
        if ("".equals(this.action)) {
            // Default action
            this.all();
        } else if ("all".equals(this.action)) {
            this.all();
        } else if ("show".equals(this.action)) {
            this.show();
        } else if ("getStep".equals(this.action)) {
            this.show();
        }
    }

    private void all() {

        List<Step> steps = stepPm.getAll();
        this.render(steps);

    }

    private void show() {


        if (parameters.length > 0) {

            int tutID;
            int stepOrder;
            try { // Param 0 = tutorialID och param 1 = steporder
                tutID = Integer.parseInt(parameters[0]);
            } catch (Exception ex) {
                tutID = -1;
            }
            try { // Param 0 = tutorialID och param 1 = steporder
                stepOrder = Integer.parseInt(parameters[1]);
            } catch (Exception ex) {
                stepOrder = -1;
            }
            if (tutID > 0) {
                Tutorial tutorial = tutPm.get(Long.valueOf(tutID));
                for (Step s : tutorial.getSteps()) {
                    if (s.getStepOrder() == stepOrder) {
                        this.render(s);
                    }
                }
//                Step step = stepPm.getFromTutId(Long.valueOf(tutID), stepOrder);
//                this.render(step);
            } else {
                this.niceDie("Step ID must be an integer!", 400);
            }
        } else {
            this.niceDie("Step ID missing!", 400);
        }
    }
}
